const domelIndicator = document.querySelector("#indicator")
const domelRecur = document.querySelector("#recur")
const domelSelect = document.querySelector("#browsers")
retrieveTabs()

domelRecur.onclick = retrieveData

function delay(tabs, index, windowId, millisecond) {
  if (index >= tabs.length) return

  new Promise((resolve, reject) => {
    setTimeout(() => {
      chrome.tabs.create(
        {
          url: tabs[index].url,
          active: tabs[index].active,
          windowId
        },
        resolve
      )
    }, millisecond)
  })
    .then(() => delay(tabs, ++index, windowId, millisecond))
    .catch(e => console.error(e))
}

function retrieveData(browser) {
  axios({
    method: "post",
    url: "get-tabs",
    data: { browser: domelSelect.options[domelSelect.selectedIndex].value }
  }).then(({ data }) => {
    // restore tabs
    Object.values(data).forEach(tabs => {
      chrome.windows.create(
        {
          url: tabs[0].url,
          width: tabs[0].width
        },
        window => {
          delay(tabs, 1, window.id, 600)
        }
      )
    })
  })
}

// initialize connection
function retrieveTabs() {
  Object.assign(axios.defaults, {
    baseURL: "http://localhost:3000"
  })

  axios
    .post("/query-db")
    .then(response => {
      response.data.forEach(({ name }) => {
        genEl("option", name, "#browsers").setAttribute("value", name)
      })

      domelIndicator.style.backgroundColor = "rgb(53,204,75)"
    })
    .catch(e => {
      domelIndicator.style.backgroundColor = "grey"
    })
}

// create element
function genEl(element, html, appendToEl) {
  const el = document.createElement(element)
  el.innerHTML = html

  if (appendToEl) {
    document.querySelector(appendToEl).appendChild(el)
  }

  return el
}

function sortTab(tabs) {
  let windows = {}
  tabs.map(tab => filterTab(tab)).forEach(tab => {
    const windowId = new String(tab.windowId)
    if (windows.hasOwnProperty(windowId)) {
      windows[windowId].push(tab)
    } else {
      windows[windowId] = []
      windows[windowId].push(tab)
    }
  })

  return windows
}

function filterTab({ active, url, windowId, highlighted, width }) {
  return { active, url, windowId, highlighted, width }
}

function syncTabs() {
  chrome.tabs.query({}, tabs => {
    tabs = sortTab(tabs)

    axios({
      url: "/push",
      method: "post",
      data: {
        tabs: tabs,
        browser: {
          name: platform.name,
          version: platform.version,
          os: platform.os
        }
      }
    })
      .then(response => {
        console.info(response.status)
        console.info(response.data)
      })
      .catch(e => {
        console.error(e)
      })
  })
}

document.querySelector("#sync").addEventListener("click", e => {
  syncTabs()
})
